/**
 * jims
 */
package com.jims.master.modules.finance.service;

import com.jims.master.common.mapper.JsonMapper;
import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.DateUtils;
import com.jims.master.common.utils.NumberUtils;
import com.jims.master.common.utils.PrintPdfUtils;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.doctor.dao.PatVisitDao;
import com.jims.master.modules.doctor.entity.PatVisit;
import com.jims.master.modules.finance.dao.InpSettleDetailDao;
import com.jims.master.modules.finance.dao.InpSettleMasterDao;
import com.jims.master.modules.finance.dao.PatPrepaymentDao;
import com.jims.master.modules.finance.entity.InpPaymentsMoney;
import com.jims.master.modules.finance.entity.InpSettleDetail;
import com.jims.master.modules.finance.entity.InpSettleMaster;
import com.jims.master.modules.finance.entity.PatPrepayment;
import com.jims.master.modules.sys.dao.CompanyDao;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.utils.DictUtils;
import com.jims.master.modules.sys.utils.UserUtils;
import com.jims.master.modules.utils.NumberToCN;
import com.sun.corba.se.spi.ior.ObjectKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 结算主记录Service
 * @author 赵宁
 * @version 2017-03-29
 */
@Service
@Transactional(readOnly = true)
public class InpSettleMasterService extends CrudService<InpSettleMasterDao, InpSettleMaster> {
	@Autowired
    private PatVisitDao patvisitDao;
	@Autowired
	private InpSettleDetailDao inpSettleDetailDao;
    @Autowired
    private InpSettleMasterDao inpSettleMasterDao;

	@Autowired
	private CompanyDao  companyDao;
	@Autowired
	private PatPrepaymentDao patPrepaymentDao;
	public InpSettleMaster get(String id) {
		return super.get(id);
	}
	
	public List<InpSettleMaster> findList(InpSettleMaster inpSettleMaster) {
		return super.findList(inpSettleMaster);
	}
	
	public Page<InpSettleMaster> findPage(Page<InpSettleMaster> page, InpSettleMaster inpSettleMaster) {
		return super.findPage(page, inpSettleMaster);
	}
    /**
     * 医保住院数据传输查询
     * @return
     */
    public Page<InpSettleMaster> findPageMedicalInsurance(Page<InpSettleMaster> page, InpSettleMaster inpSettleMaster) {

        inpSettleMaster.setPage(page);
        Page<InpSettleMaster> inpSettleMasterPage = page.setList(inpSettleMasterDao.findPageMedicalInsurance(inpSettleMaster));
        return inpSettleMasterPage;
    }
	/**
	 * 出院结算计算优惠
	 * @param visitNo
	 * @param chargeType
	 * @return String
	 * @author 赵宁
	 */
	@Transactional(readOnly = false)
    public String outPreferCalcul(String visitNo,String chargeType){
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("chargeType",chargeType);
		map.put("visitNo",visitNo);
		map.put("orgId",UserUtils.getOrgId());
		map.put("ret", "1123456");
		dao.outPreferCalcul(map);
		return (String)map.get("ret");
	}
	/**
	 * 出院结算
	 * @param visitNo
	 * @param payType
	 * @return
	 * @author 赵宁
	 */
	@Transactional(readOnly = false)
	public Map<String,Object>  save(String visitNo,String payType,String payMoney,String changes) {
		PatVisit patVisit = patvisitDao.findPatVisitByVisitNo(visitNo, UserUtils.getOrgId());
		String patientId= patVisit.getPatientId();
		String visitId = patVisit.getId();
		User user = UserUtils.getUser();
		String [] types=payType.split(",");

		String rcptNo= NumberUtils.getRcptNo();
		//拼接支付类型和金额
		String [] moneys = payMoney.split(",");
		String typeJson="[";
		for(int j=0;j<types.length;j++){
			String type=types[j];
			String money = "";
			if(moneys[j]!=null && !moneys[j].equals("")){
				money = moneys[j];
			}else{
				money="-"+changes;
			}
			typeJson+= "{\"payType\":\""+types[j]+"\",\"money\":\""+money+"\"},";
		}
		typeJson = typeJson.substring(0,typeJson.length()-1)+"]";
		String jsonInfo="{";
		jsonInfo+="\"patientId\":\""+patientId+"\",";
		jsonInfo+="\"visitId\":\""+visitId+"\",";
		jsonInfo+="\"type\":"+typeJson+",";//支付类型
		jsonInfo+="\"rcptNo\":\""+rcptNo+"\"";//rcptNo
		jsonInfo+="}";
		//登录人信息
		String loginInfoJson = JsonMapper.toJsonString(user);
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("jsonInfo",jsonInfo);
		map.put("loginInfo",loginInfoJson);
		map.put("ret", "1123456");
		dao.confirmSettle(map);
		Map<String ,Object> resultMap= new HashMap<>();
		resultMap.put("return",map.get("ret"));
		resultMap.put("rcptNo",rcptNo);
		return resultMap ;
	}

	/**
	 * 根据收据号查询 主记录
	 * @param rcptNo
	 * @param orgId
	 * @return
	 * @author 赵宁
	 */
	public InpSettleMaster getMasterByRcpt(String rcptNo,String orgId){
	    return  dao.getMasterByRcpt(rcptNo,orgId);
	}

	/**
	 * 获取结算类型
	 * @param rcptNo
	 * @param orgId
	 * @return
	 * @author 赵宁
	 */
	public InpSettleMaster getSettleType(String rcptNo,String orgId){
		return dao.getMaster(rcptNo, orgId);
	}

	/**
	 * 取消结算
	 * @param rcptNo
	 * @return
	 * @author 赵宁
	 */
	@Transactional(readOnly = false)
	public String cancelSettle(String rcptNo){
		String newRcptNo= NumberUtils.getRcptNo();
		String jsonInfo="{";
		jsonInfo+="\"old\":\""+rcptNo+"\",";
		jsonInfo+="\"new\":"+newRcptNo;
		jsonInfo+="}";
		//登录人信息
		String loginInfoJson = JsonMapper.toJsonString(UserUtils.getUser());
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("jsonInfo",jsonInfo);
		map.put("loginInfo",loginInfoJson);
		map.put("ret", "1123456");
        dao.cancelSettle(map);
		return (String)map.get("ret") ;
	}

	/**
	 * 查询结算明细
	 * @param rcptNo
	 * @return
	 * @author 赵宁
	 */
	public List<InpSettleDetail> getDetails(String rcptNo,String orgId){
		InpSettleMaster inpSettleMaster=dao.getMaster(rcptNo, orgId);
		InpSettleDetail inpSettleDetail = new InpSettleDetail();
		inpSettleDetail.setMasterId(inpSettleMaster.getId());
		inpSettleDetail.setRcptNo(rcptNo);
		inpSettleDetail.setOrgId(orgId);
		return inpSettleDetailDao.findDetails(inpSettleDetail);
	}

	/**
	 * 出院结算打印
	 * @param inpSettleMaster
	 * @return
	 * @author 赵宁
	 */
	public String settlePrint(InpSettleMaster inpSettleMaster){
		User user = UserUtils.getUser();
        String printPath="";
		Double cost = 0.00;
		String hospital = companyDao.get(user.getOrgId()).getOrgName();
        InpSettleMaster master =dao.getMaster(inpSettleMaster.getRcptNo(),user.getOrgId());
		Map<String ,Object> map=new HashMap<>();
		map.put("date",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
		map.put("hospital",hospital);
		map.put("userName",user.getName());
		map.put("inpNo",master.getPatVisit().getVisitNo());
		map.put("admissionDateTime", DateUtils.formatDateTime(master.getPatVisit().getAdmissionDate()));
		if(master.getPatVisit().getDischargeDate()!=null){
			map.put("dischargeDateTime",DateUtils.formatDateTime(master.getPatVisit().getDischargeDate()));
		}
		if(master.getPatVisit().getAdmissionDate()!=null && master.getPatVisit().getDischargeDate()!=null){
			map.put("count",DateUtils.getDistanceOfTwoDate(master.getPatVisit().getAdmissionDate(),master.getPatVisit().getDischargeDate()));
		}else{
			map.put("count",DateUtils.pastDays(master.getPatVisit().getAdmissionDate()));
		}
		map.put("deptName", master.getPatVisit().getDeptAdmissionTo());
        map.put("name",master.getPatVisit().getPatVisitIndex().getName());
		map.put("sex", DictUtils.getDictLabel(master.getPatVisit().getPatVisitIndex().getSex(),"SEX_DICT",""));
		map.put("insuranceType",DictUtils.getDictLabel(master.getPatVisit().getPatVisitIndex().getChargeType(), "CHARGE_TYPE_DICT",""));
        List<InpSettleDetail> inpSettleDetails=master.getInpSettleDetailList();
		if(inpSettleDetails.size()>0){
			for(int i=0;i<inpSettleDetails.size();i++){
				Double m=Double.valueOf(String.valueOf(inpSettleDetails.get(i).getPayments()));
				cost=cost+m;
			}
		}
        map.put("costs",cost);
		PatPrepayment patPrepayment = new PatPrepayment();
		patPrepayment.setVisitId(master.getPatVisit().getId());
		patPrepayment.setOrgId(user.getOrgId());
		PatPrepayment payments = patPrepaymentDao.printPayments(patPrepayment);
		Integer paymentsMoney =payments.getMoney();
		map.put("prepayment",paymentsMoney);
		map.put("refund",paymentsMoney-cost);
		BigDecimal numberOfMoney = new BigDecimal(cost);
		String s = NumberToCN.number2CNMontrayUnit(numberOfMoney);
		map.put("capital",s.toString());
		InpSettleDetail inpSettleDetail= new InpSettleDetail();
		inpSettleDetail.setOrgId(user.getOrgId());
		inpSettleDetail.setRcptNo(master.getRcptNo());
		List<BaseDto> list= inpSettleDetailDao.findSettleDetails(inpSettleDetail);
        printPath = PrintPdfUtils.previewPdf(user.getId(), "his/finance/inpPatientCharge.jasper", map, list, "inpPatientCharge");
	    return printPath;
	}
}